package com.tbit.main.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.extern.slf4j.Slf4j;

import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;

/**
 * Md5加密方法
 *
 * @author jing
 */
@Slf4j
public class Md5Utils {

    private static byte[] md5(String s) {
        MessageDigest algorithm;
        try {
            algorithm = MessageDigest.getInstance("MD5");
            algorithm.reset();
            algorithm.update(s.getBytes("UTF-8"));
            byte[] messageDigest = algorithm.digest();
            return messageDigest;
        } catch (Exception e) {
            log.error("MD5 Error...", e);
        }
        return null;
    }

    private static final String toHex(byte hash[]) {
        if (hash == null) {
            return null;
        }
        StringBuffer buf = new StringBuffer(hash.length * 2);
        int i;

        for (i = 0; i < hash.length; i++) {
            if ((hash[i] & 0xff) < 0x10) {
                buf.append("0");
            }
            buf.append(Long.toString(hash[i] & 0xff, 16));
        }
        return buf.toString();
    }

    public static String hash(String s) {
        try {
            return new String(toHex(md5(s)).getBytes("UTF-8"), "UTF-8");
        } catch (Exception e) {
            log.error("not supported charset...{}", e);
            return s;
        }
    }


    public static void main(String[] args) throws JsonProcessingException {
        Map<String, String> head = new HashMap<>();
        long ts = System.currentTimeMillis();
        //long ts = 1690874250261L;
        System.out.println(ts);
        //appKey
        String appkey = "ECB83FC1DA724196A270E8A904AE0275";
        //秘钥
        String appSecret = "46D4B7467C366D54D9066C722259CC7F";
        head.put("appkey", appkey);
        String appKeyString = String.format("%s.%d.%s.%d.%s", appkey, ts, appSecret, ts, appkey);
        System.out.println(appKeyString);
        head.put("sign", Md5Utils.hash(appKeyString));
        head.put("ts", String.valueOf(ts));
        System.out.println(head);
    }
}

